package com.zzhua.config;

import com.zzhua.pojo.User;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.SessionListener;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.concurrent.CopyOnWriteArrayList;

@Primary
@Component
public class MySessionListener implements SessionListener {

    private static CopyOnWriteArrayList<Session> sessions = new CopyOnWriteArrayList<>();

    public static CopyOnWriteArrayList<Session> getSessions() {
        return sessions;
    }

    // 拥有身份，创建session
    @Override
    public void onStart(Session session) {
        sessions.add(session);
    }

    // ================检测session周期：默认一个小时=====================

    // 检测session valid
    @Override
    public void onStop(Session session) {
        sessions.removeIf(s -> {
            boolean flag = Objects.equals(session.getId(), s.getId());
            Object principals = session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
            if (principals != null) {
                Object primaryPrincipal = ((PrincipalCollection) principals).getPrimaryPrincipal();
                User user = (User) primaryPrincipal;
                System.out.println(user.getName() + " 账号已被停用");
            }
            return flag;
        });
    }

    // 检测session过期
    @Override
    public void onExpiration(Session session) {
        sessions.removeIf(s -> {
            boolean flag = Objects.equals(session.getId(), s.getId());
            Object principals = session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
            if (principals != null) {
                Object primaryPrincipal = ((PrincipalCollection) principals).getPrimaryPrincipal();
                User user = (User) primaryPrincipal;
                System.out.println(user.getName() + " 账号已过期");
            }
            return flag;
        });
    }
}
